<template>
    <div>
        <el-card class="box-card">
            <el-tree :data="categoryList" node-key="id" :props="defaultProps" default-expand-all
                :expand-on-click-node="false">
                <template #default="{ node, data }">
                    <span class="custom-tree-node">
                        <span>
                            <el-image :src="data.picUrl" 
                                v-if="data.picUrl" />
                            <span>{{ data.title }}</span>
                            <el-tag size="small" type="danger" v-if="data.level === 0">一级</el-tag>
                            <el-tag size="small" type="warning" v-else-if="data.level === 1">二级</el-tag>
                            <el-tag size="small" type="success" v-else-if="data.level === 2">三级</el-tag>
                        </span>
                        <span>
                            <el-button type="primary" round size="small" v-show="data.level !== 2"
                                @click="handleAddCategory(data)" v-permission="'product:category:create'">添加</el-button>
                            <el-button type="warning" round size="small" v-show="data.id !== 0" @click="handleEditCategory(data)" v-permission="'product:category:edit'">编辑</el-button>
                            <el-button type="danger" round size="small"
                                v-show="!data.childrenList || data.childrenList.length <= 0" @click="handleDeleteCategory(data.id)" v-permission="'product:category:delete'">删除</el-button>
                        </span>
                    </span>
                </template>
            </el-tree>
        </el-card>
        <!-- 对话框 -->
        <el-dialog v-model="dialogFormVisible" :title="ruleForm.title" @close="handleCloseDialog">
            <el-form ref="ruleFormRef" :model="ruleForm.data" :rules="rules" label-width="120px">
                <el-form-item label="类目名称" prop="title">
                    <el-input v-model="ruleForm.data.title" placeholder="请输入类目名称" />
                </el-form-item>
                <el-form-item label="类目名称">
                    <el-upload class="avatar-uploader" :action="uploadPath" :headers="headers" :show-file-list="false"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="ruleForm.data.picUrl" :src="ruleForm.data.picUrl" class="avatar" width="178" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm(ruleFormRef)">
                        确定
                    </el-button>
                    <el-button @click="resetForm(ruleFormRef)">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import { post, host } from '@/utils/http'
import { ElMessage, ElMessageBox } from 'element-plus';
import { ref, reactive, onMounted, computed } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import cookies from 'js-cookie'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import { ClassCategory,EnumDialogTitle } from '#/index';

//类目数据
const categoryList = ref([{} as ClassCategory])
//设置树结构属性
const defaultProps = {
    label: 'title',
    children: 'childrenList'
}
//是否显示对话框
const dialogFormVisible = ref(false)
//上传图片路径
const uploadPath = host + "/upload/admin"
//文件上传请求头
const headers = computed(() => {
    return {
        ADMINTOKEN: cookies.get("adminToken")
    }
})
//form表单节点
const ruleFormRef = ref<FormInstance>()
//form表单对象
const ruleForm = reactive({
    title:EnumDialogTitle.create,
    data:new ClassCategory()
})
//form表单校验规则
const rules = reactive<FormRules>({
    title: [{ required: true, message: '请输入类目名称', trigger: 'blur' }]
})

/**
 * 生命周期获取数据
 */
onMounted(() => {
    getCategoryList()
})
/**
 * 获取类目数据列表
 */
function getCategoryList() {
    const data = { _gp: 'category', _mt: 'categoryList' }
    post(data).then(res => {
        const { data, errno, errmsg } = res
        if (200 === errno) {
            categoryList.value = [{ title: '全部类目', id: 0, childrenList: [...data] } as ClassCategory]
        } else {
            ElMessage.error(errmsg)
        }
    })
}
/**
 * 添加时对话框
 * @param row 当前行对象
 */
function handleAddCategory(row: ClassCategory) {
    ruleForm.title = EnumDialogTitle.create
    dialogFormVisible.value = true
    ruleForm.data.parentId = row.id
}
/**
 * 编辑时对话框
 * @param row 当前行对象
 */
function handleEditCategory(row: ClassCategory){
    ruleForm.title = EnumDialogTitle.edit
    dialogFormVisible.value = true
    Object.assign(ruleForm.data,row)
}
/**
 * 上传图片成功回调
 */
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    ruleForm.data.picUrl = response.url
}
/**
 * 上传图片前钩子
 */
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('图片格式必须是jpg!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片大小不能超过2MB!')
        return false
    }
    return true
}
/**
 * 编辑和添加的提交功能
 */
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log(ruleForm.data)
      let mt = ruleForm.title =='创建'?'create':'update'
      const data = {_gp:'admin.category',_mt:mt,...ruleForm.data}
      post(data).then(res=>{
        const {errno} = res
        if(200 == errno){
            ElMessage.success(ruleForm.title+'成功')
            dialogFormVisible.value = false
            getCategoryList()
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}
/**
 * 取消
 */
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  dialogFormVisible.value = false
}
/**
 * 关闭对话框
 */
function handleCloseDialog(){
    ruleForm.data = new ClassCategory()
    ruleFormRef.value?.resetFields()
}
/**
 * 删除
 * @param id 当前行id
 */
function handleDeleteCategory(id:number){
    ElMessageBox.confirm(
    '是否删除该行数据?',
    '删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
      const data = {_gp:'admin.category',_mt:'delete',id}
      post(data).then(res=>{
        const {errno,errmsg} = res
        if(200 === errno){
            ElMessage.success('删除成功')
            getCategoryList()
        }else{
            ElMessage.error(errmsg)
        }
      })
    }).catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
</script>
<style lang="less" scoped>
.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 5px;

    .el-tag {
        margin-left: 8px;
    }

    .el-image {
        vertical-align: bottom;
    }
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
:deep(.el-tree-node__content) {
  height: auto;
  margin-top: 10px;
  .el-image {
    vertical-align: middle;
    width: 30px; 
    height: 30px;
    margin-right: 8px;
  }
}
</style>

<style lang="less">
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
